﻿using Core.Info;
using Core.Utility.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Config
{
    /// <summary>
    /// 应用Json配置抽象类，用于存储应用某些需要独立存储的JSON配置
    /// </summary>
    public abstract class AppJsonConfig: IAppJsonConfig
    {
        /// <summary>
        /// 配置文件路径
        /// </summary>
        public abstract string ConfigFilePath { get; protected set; } //= Path.Combine(AppInfo.ConfigDirectory,
            //$"{NamespaceHelper.ToJoinStringLowerNamespace(typeof(AppJsonConfig).FullName ?? nameof(AppJsonConfig), ".")}.config.json");

        /// <summary>
        /// 基础配置节
        /// </summary>
        public abstract string BaseConfigSection { get; protected set; } //= $"{nameof(AppJsonConfig)}.BaseConfig";

        /// <summary>
        /// 默认构造
        /// </summary>
        /// <param name="isLoadConfig">是否加载配置</param>
        public AppJsonConfig(bool isLoadConfig = false)
        {
            if (isLoadConfig)
            {
                LoadConfig();
            }
        }

        /// <summary>
        /// (从配置文件中)加载配置
        /// </summary>
        public abstract void LoadConfig();

        /// <summary>
        /// 保存配置(到配置文件)
        /// </summary>
        public abstract void SaveConfig();

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public virtual T? GetJsonConfig<T>(string key, T? defaultValue = default(T))
        {
            return JsonConfigHelper.GetJsonConfigByFileFullPath<T>(ConfigFilePath, BaseConfigSection, key, defaultValue);
        }

        /// <summary>
        /// 设置Json配置，通过文件全路径
        /// </summary>
        /// <param name="key">配置节的key，不区分大小写,不能为空，否则抛出异常</param>
        /// <param name="value">设置配置的值</param>
        /// <returns></returns>
        public virtual bool SetJsonConfig<T>(string key, T? value = default(T))
        {
            return JsonConfigHelper.SetJsonConfigByFileFullPath<T>(ConfigFilePath, BaseConfigSection, key, value);
        }

    }

    /// <summary>
    /// 应用配置
    /// </summary>
    public interface IAppJsonConfig
    {
        /// <summary>
        /// 配置路径
        /// </summary>
        string ConfigFilePath { get; }

        /// <summary>
        /// 基础配置节
        /// </summary>
        string BaseConfigSection { get; }

        /// <summary>
        /// 加载配置
        /// </summary>
        void LoadConfig();

        /// <summary>
        /// 保存配置
        /// </summary>
        void SaveConfig();
    }
}
